package com.yeepay.yop.sdk.service.aggpay.notify;

import com.google.common.collect.Maps;
import com.yeepay.yop.sdk.http.YopContentType;
import com.yeepay.yop.sdk.service.common.YopCallbackEngine;
import com.yeepay.yop.sdk.service.common.callback.YopCallback;
import com.yeepay.yop.sdk.service.common.callback.YopCallbackRequest;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Enumeration;
import java.util.Map;

public class YopNotifyUtil {

    /**
     * @description: 获取请求头
     */
    public static Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> result = Maps.newHashMap();
        final Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String headerName = headerNames.nextElement();
            final String headerValue = request.getHeader(headerName);
            result.put(headerName, headerValue);
        }
        return result;
    }

    /**
     * 基于上一步接收到的原始报文，解密后得到业务数据
     *
     * @param reqMethod 请求方法，如POST
     * @param reqURI 请求路径, 如/rest/xxx，不包含query参数
     * @param reqHeaders 请求头
     * @param jsonReqBody json请求体
     */
    public static String decryptSm2Callback(String reqMethod, String reqURI,
                                      Map<String, String> reqHeaders, String jsonReqBody) {
        YopCallbackRequest callbackReq = new YopCallbackRequest(reqURI, reqMethod)
                .setContentType(YopContentType.JSON)
                .setHeaders(reqHeaders).setContent(jsonReqBody);

        YopCallback callback = YopCallbackEngine.parse(callbackReq);
        return callback.getBizData();
    }
}
